package com.fx.server.auth;

import com.fx.server.comm.ValidateCodeException;
import com.fx.server.server.CacheImageCodeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class FxImageCodeCheckFilter extends OncePerRequestFilter {

    @Autowired
    private CacheImageCodeService cacheImageCodeService;

    @Autowired
    private FxAuthenticationEntryPoint fxAuthenticationEntryPoint;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {
        if(antPathMatcher.match("/auth/login",request.getRequestURI())
                && StringUtils.equalsAnyIgnoreCase(request.getMethod(),"post")){
            try {
                validateCode(request);
            }catch (ValidateCodeException e){
                fxAuthenticationEntryPoint.commence(request,response,e);
                return;
            }
        }
        chain.doFilter(request,response);
    }

    private void validateCode(HttpServletRequest request) {

        String captcha = obtainImageCode(request);
        String t = obtainT(request);
        // 验证验证码
        if (StringUtils.isBlank(captcha)) {
            throw new ValidateCodeException("验证码不能为空");
        }
        // 从redis中获取之前保存的验证码跟前台传来的验证码进行匹配
        String kaptcha = cacheImageCodeService.imageCode(t);
        if (kaptcha == null) {
            throw new ValidateCodeException("验证码已失效");
        }
        if (!captcha.toLowerCase().equals(kaptcha)) {
            throw new ValidateCodeException("验证码错误");
        }
    }

    /**
     * 获取前端传来的图片验证码
     *
     * @param request
     * @return
     */
    private String obtainImageCode(HttpServletRequest request) {
        String imageCode = "code";
        return request.getParameter(imageCode);
    }


    /**
     * 获取前端传来的图片验证码
     *
     * @param request
     * @return
     */
    private String obtainT(HttpServletRequest request) {
        String token = "key";
        return request.getParameter(token);
    }
}
